
package view;

import controllers.EMailControl;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;

/**
 *
 * @author john
 */
public class ContactDialog extends CustomizedStage {
    
    private final GridPane grid;
    private final TextField subjectTF;
    private final TextField emailTF;
    private final TextArea messageTA;
    private final Label subjectL;
    private final Label emailL;
    private final Label messageL;
    private final Button sendB;
    private final Button cancelB;
    
    private Tooltip emptySubjectT;
    private Tooltip emptyEmailT;
    private Tooltip wrongEmailT;
    private Tooltip emptyMessageT;
    
    private boolean loginIssue;
    
    public ContactDialog(Stage owner, boolean loginIssue){
        this(owner,0,0,loginIssue);
    }

    public ContactDialog(Stage owner, double width, double height, boolean loginIssue) {
        super(owner, "Contacto con el administrador", width, height);
        this.loginIssue=loginIssue;
        grid=new GridPane();
        grid.setPadding(new Insets(20));
        grid.setHgap(10);
        grid.setVgap(6);
        
        subjectL=new Label("Asunto");
        subjectTF=new TextField(loginIssue?"No puedo iniciar sesión":"");
        emailL=new Label("Email");
        emailTF=new TextField();
        emailTF.setPromptText("ejemplo@dominio.com");
        messageL=new Label("Mensaje");
        messageTA=new TextArea(loginIssue?"Ingreso mi usuario y contraseña de siempre y no puedo iniciar sesión.":"\n");
        messageTA.setMinSize(300, 200);
        sendB=new Button("Enviar");
        sendB.setOnAction(sendAction());
        cancelB=new Button("Cancelar");
        cancelB.setOnAction(cancelAction());
        HBox buttonsHBox=new HBox(7);
        GridPane.setHalignment(buttonsHBox, HPos.RIGHT);
        GridPane.setMargin(buttonsHBox, new Insets(2, 0, 0, 0));
        buttonsHBox.getChildren().addAll(sendB,cancelB);
        initTooltips();
        if(loginIssue){
            setOnCloseRequest(new EventHandler<WindowEvent>() {
                @Override
                public void handle(WindowEvent t) {
                    Platform.exit();
                    System.exit(0);
                }
            });
        }
        else
            setOnClose(HIDE);
        grid.add(subjectL, 0, 0);
        grid.add(subjectTF, 0, 1);
        grid.add(emailL, 0, 2);
        grid.add(emailTF, 0, 3);
        grid.add(messageL, 0, 4);
        grid.add(messageTA, 0, 5);
        grid.add(buttonsHBox, 0, 6);
        
        subjectTF.setOnKeyTyped(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent event) {
                if(emptySubjectT.isShowing())
                    emptySubjectT.hide();
            }
        });
        subjectTF.setOnKeyReleased(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent event) {
                if(event.getCode().toString().equals("ENTER")){
                    emailTF.requestFocus();
                    emailTF.selectAll();
                }
            }
        });
        emailTF.setOnKeyTyped(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent event) {
                if(emptyEmailT.isShowing())
                    emptyEmailT.hide();
                if(wrongEmailT.isShowing())
                    wrongEmailT.hide();
            }
        });
        emailTF.setOnKeyReleased(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent event) {
                if(event.getCode().toString().equals("ENTER")){
                    messageTA.requestFocus();
                    messageTA.end();
                }
            }
        });
        messageTA.setOnKeyTyped(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent event) {
                if(emptyMessageT.isShowing())
                    emptyMessageT.hide();
            }
        });
        
        setContent(grid);
    }
        
    /**
     * 
     */
    private void initTooltips(){
       emptySubjectT=TooltipBuilder.create()
            .text("Indique el asunto del mensaje")
            .hideOnEscape(true)
            .autoHide(true)
            .build();
       emptyEmailT=TooltipBuilder.create()
            .text("El email es necesario para que el administrador pueda responder su inquietud.")
            .hideOnEscape(true)
            .autoHide(true)
            .build();
       wrongEmailT=TooltipBuilder.create()
            .text("No es una dirección válida")
            .hideOnEscape(true)
            .autoHide(true)
            .build();
       emptyMessageT=TooltipBuilder.create()
            .text("El mensaje no puede estar vacio")
            .hideOnEscape(true)
            .autoHide(true)
            .build();
    }
    
    /**
     * 
     */
    public void showStage(){
        show();
        subjectTF.requestFocus();
        subjectTF.end();
    }
    
    /**
     * 
     * @return 
     */
    private EventHandler<ActionEvent> sendAction(){
        return new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                boolean sendEmail=true;
                boolean checkEmailAddress=true;
                Node empty=null;
                if(subjectTF.getText().trim().equals("")){
                    emptySubjectT.show(subjectTF, 
                        getX()+subjectTF.getLayoutX()+subjectTF.getWidth(),
                        getY()+subjectTF.getLayoutY()+25);
                    empty=subjectTF;
                    sendEmail=false;
                }
                if(emailTF.getText().trim().equals("")){
                    emptyEmailT.show(emailTF, 
                        getX()+emailTF.getLayoutX()+emailTF.getWidth(),
                        getY()+emailTF.getLayoutY()+25);
                    if(empty==null)
                        empty=emailTF;
                    sendEmail=checkEmailAddress=false;
                }
                if(messageTA.getText().trim().equals("")){
                    emptyMessageT.show(messageTA, 
                        getX()+messageTA.getLayoutX()+messageTA.getWidth(),
                        getY()+messageTA.getLayoutY()+25);
                    if(empty==null)
                        empty=messageTA;
                    sendEmail=false;
                }
                if(checkEmailAddress){
                    if(!EMailControl.validEmail(emailTF.getText().trim())){
                        wrongEmailT.show(emailTF, 
                            getX()+emailTF.getLayoutX()+emailTF.getWidth(),
                            getY()+emailTF.getLayoutY()+25);
                        sendEmail=false;
                    }
                }
                if(sendEmail){
                    String subject=subjectTF.getText().trim();
                    String email=emailTF.getText().trim();
                    String message=messageTA.getText();
                    boolean res = EMailControl.sendMail(subject, message, email);
                    if (res) {
                        System.out.println("El mensaje ha sido enviado.");
                    } else {
                        System.err.println("NO se puede enviar el mensaje, revise la conexion  internet.");
                    }
                }else{
                    if(empty!=null)
                        empty.requestFocus();
                    else{
                        emailTF.requestFocus();
                        emailTF.selectAll();
                    }
                }
            }
        };
    }
    
    /**
     * 
     * @return 
     */
    private EventHandler<ActionEvent> cancelAction(){
        return new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                if(loginIssue){
                    MainWindow.closeLoginContactDialog();
                    MainWindow.showLoginDialog();
                }else{
                    close();
                }
            }
        };
    }
}